package web.config;

import web.common.BaseModifier;
import web.common.CodeEngineConfig;
import web.common.XmlAccessUtil;
import org.dom4j.Element;

import java.util.TreeMap;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: duanbin
 * Date: 2007-8-22
 * Time: 11:11:07
 * To change this template use File | Settings | File Templates.
 */
public class SecurityBeanModifier extends BaseModifier {
    public static final String ROLE_ADMIN = "ROLE_ADMIN";

    public String getFileName() {
        return CodeEngineConfig.getSpringSecurityFile();
    }
    public void doModify(String name) {
        //step 1. Add controller definitions
        //NOTES: hardcode using 'ns' as default namespace
        Element element = (Element) getXPath4DefaultNS("//ns:bean[@id='filterInvocationInterceptor']/ns:property[@name='objectDefinitionSource']/ns:value").selectSingleNode(doc);
        String ovs = element.getText();
        String url = "/" + name.toLowerCase() + "/*.v";
        String roles = ROLE_ADMIN;
        String map = url + "=" + roles;

        List list = XmlAccessUtil.stringToken2List(ovs,"\n");
        int i = checkExist(list, url);
        if(i!=-1){
            list.set(i,map);
        }else{
            Object lastObj = list.get(list.size()-1);
            list.remove(lastObj);
            list.add(map);
            list.add(lastObj);
        }
        String dvs = XmlAccessUtil.list2String(list);
        element.setText(dvs);
     }
     private int checkExist(List list, String url){
         for(int i=0; i<list.size(); i++){
             if(((String)list.get(i)).indexOf(url)!=-1){
                 return i;
             }
         }
         return -1;
     }
}
